package com.daodway.designpattern.statepattern;

public class StateMachine<T> {
	private T m_pOwner;
	private State<T> m_pCurrentState;
	private State<T> m_pPreviousState;
	private State<T> m_pGlobalState;
	public StateMachine(T owner){
		m_pOwner =owner;
		m_pCurrentState=null;
		m_pPreviousState=null;
		m_pGlobalState=null;
	}
	public void setM_pCurrentState(State<T> m_pCurrentState) {
		this.m_pCurrentState = m_pCurrentState;
	}
	public void setM_pPreviousState(State<T> m_pPreviousState) {
		this.m_pPreviousState = m_pPreviousState;
	}
	public void setM_pGlobalState(State<T> m_pGlobalState) {
		this.m_pGlobalState = m_pGlobalState;
	}
	
	public void Update(){
		if(m_pGlobalState!=null){
			m_pGlobalState.Execute(m_pOwner);
		}
		if(m_pCurrentState!=null){
			m_pCurrentState.Execute(m_pOwner);
		}
	}
	public void ChangeState(State<T> pNewState){
		m_pPreviousState=m_pCurrentState;
		m_pCurrentState.Exit(m_pOwner);
		m_pCurrentState=pNewState;
		m_pCurrentState.Enter(m_pOwner);
	}
	public void RevertToPerviousState(){
		ChangeState(m_pPreviousState);
	}
	public State<T> getM_pCurrentState() {
		return m_pCurrentState;
	}
	public State<T> getM_pPreviousState() {
		return m_pPreviousState;
	}
	public State<T> getM_pGlobalState() {
		return m_pGlobalState;
	}
	public boolean isInState(State<T> st){
		boolean flag=false;
		if (st.getClass() == m_pCurrentState.getClass()) {
			flag=true;
		}
		return flag;
	}
	public boolean HandleMessage(Telegram msg){
		if(m_pGlobalState!=null&&m_pGlobalState.OnMessage(m_pOwner, msg)){
			return true;
		}
		if(m_pCurrentState!=null&&m_pCurrentState.OnMessage(m_pOwner, msg)){
			return true;
		}
		return false;
	}
}
